import type { FormInstance, FormItemProp } from "element-plus";
import { clone } from "@pureadmin/utils";
import { ref } from "vue";
import { message } from "@/utils/message";
// import { useUserStoreHook } from "@/store/modules/user";
import { 检查是否已经注册api, 发送短信api } from "@/api/auth";

const isDisabled = ref(false);
const timer = ref(null);
const text = ref("");

export const useVerifyCode = () => {
  const start = async (
    formEl: FormInstance | undefined,
    props: FormItemProp,
    ruleForm,
    time = 60
  ) => {
    if (!formEl) return;
    const initTime = clone(time, true);
    await formEl.validateField(props, async isValid => {
      if (isValid) {
        const res = await 检查是否已经注册api(ruleForm);
        if (res.code === 1) {
          // 检查通过开始发短信 和 倒计时👇
          const res2 = await 发送短信api(ruleForm);
          if (res2.code === 1) {
            clearInterval(timer.value);
            isDisabled.value = true;
            text.value = `${time}`;
            timer.value = setInterval(() => {
              if (time > 0) {
                time -= 1;
                text.value = `${time}`;
              } else {
                text.value = "";
                isDisabled.value = false;
                clearInterval(timer.value);
                time = initTime;
              }
            }, 1000);
          } else {
            message(res2.detail, {
              type: "error"
            });
          }
        } else {
          // alert("已经注册");
          message(res.detail, {
            type: "error"
          });
        }
        // .catch(err => {
        //   // loading.value = false;
        //   message(err.detail, {
        //     type: "warning"
        //   });
        // });
      }
    });
  };

  const end = () => {
    text.value = "";
    isDisabled.value = false;
    clearInterval(timer.value);
  };

  return {
    isDisabled,
    timer,
    text,
    start,
    end
  };
};
